package cn.slahser.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.slahser.R;
import cn.slahser.serverEntity.Message;
import cn.slahser.serverEntity.ReplyExt;
import cn.slahser.serverEntity.ShuoExt;
import cn.slahser.utils.AcionClientTCP;
import cn.slahser.utils.ButtonExt;
import cn.slahser.utils.LoginClientTCP;
import cn.slahser.utils.SlahserMetaData;

public class MainActivity extends Activity {
	/** Called when the activity is first created. */
	protected Button sendButton = null;
	protected Button imageButton = null;
	protected Button amrButton = null;
	protected Button moreButton = null;
	protected EditText shuoText = null;
	protected ScrollView scrollView = null;
	protected LinearLayout linearLayout = null;
	protected LinearLayout list_linearLayout = null;
	protected View view = null;
	protected String imageFilename = "";

	@Override
	protected void onStart() {
		super.onStart();
		// 初始化得到数据，getdata返回的是个集合，嗯
		this.fillContent(LoginClientTCP.getData());
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		this.initView();

		view = (View) LayoutInflater.from(MainActivity.this).inflate(
				R.layout.activity_main_more, null);
		final RelativeLayout.LayoutParams lay = (RelativeLayout.LayoutParams) scrollView
				.getLayoutParams();

		AcionClientTCP.action = this;

		sendButton.setOnClickListener(new sendButtonOnClickListener());
		amrButton.setOnTouchListener(new amrButtonOnTouchListener());
		imageButton.setOnClickListener(new imageButtonOnClickListener());
		// 操作集中在本activity上，姑且做个匿名内部类就是了
		moreButton.setOnClickListener(new OnClickListener() {

			// 判断加号按钮是否点下
			boolean b = true;

			@Override
			public void onClick(View v) {
				if (b) {
					// 点下加号添加view
					linearLayout.addView(view);
					int m = lay.bottomMargin + 55;
					// 得到该view对象设置属性
					lay.bottomMargin = m;
					scrollView.setLayoutParams(lay);
					// 设为减号
					moreButton.setText("━");
					b = false;
				} else {
					// 如果点下减号。。
					linearLayout.removeView(view);
					int m = lay.bottomMargin - 55;
					lay.bottomMargin = m;
					// 还是原来的配方，还是原来的味道
					scrollView.setLayoutParams(lay);
					b = true;
					moreButton.setText("+");
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 0) {
			// 开辟新线程
			new Thread() {
				public void run() {
					try {
						/***
						 * 图片的生成
						 */
						// 创建文件对象
						File f = new File(SlahserMetaData.SD_PATH
								+ File.separator + imageFilename);
						// 图片转码
						BitmapFactory.Options options = new BitmapFactory.Options();
						options.inJustDecodeBounds = true;
						// bitmap对象构建
						Bitmap bitmap = BitmapFactory.decodeFile(f.getPath(),
								options);
						options.inJustDecodeBounds = false;

						int be = (int) (options.outHeight / (float) 300);
						if (be <= 0)
							be = 1;
						options.inSampleSize = be;

						// 写出图片对象作为文件
						File file2 = new File(SlahserMetaData.SD_PATH
								+ File.separator + imageFilename);
						try {
							FileOutputStream out = new FileOutputStream(file2);
							if (bitmap.compress(Bitmap.CompressFormat.JPEG,
									100, out)) {
								out.flush();
								out.close();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}

						/***
						 * 图片的上传
						 */
						// socket对象,处理上传事宜，通过file port传递
						Socket socket = new Socket(SlahserMetaData.IP,
								SlahserMetaData.FILEPORT);

						InputStream in = socket.getInputStream();
						OutputStream out = socket.getOutputStream();
						// 符合当初约定的规范
						out.write(("upload,image," + file2.length()).getBytes());
						out.flush();
						// 缓冲
						byte[] b = new byte[1024 * 10];
						// 读入数据
						in.read(b);

						String serverInfo = new String(b).trim();
						FileInputStream fin = new FileInputStream(file2);

						int len = 0;
						while ((len = fin.read(b)) != -1) {
							// 流写出
							out.write(b, 0, len);
							out.flush();

						}
						fin.close();
						out.close();
						in.close();

						/***
						 * 返回信息的处理
						 */
						// 消息对象
						Message msg = new Message();

						if (titleid.trim().equals("")) {
							msg.setType(Message.SEND_IMAGE);
							Hashtable<String, Object> table = new Hashtable<String, Object>();
							table.put("text", serverInfo.split(",")[1]);
							table.put("userid", SlahserMetaData.userid);
							msg.setValue(table);
						} else {
							msg.setType(Message.REPLY_IMAGE);
							Hashtable<String, Object> table = new Hashtable<String, Object>();
							table.put("text", serverInfo.split(",")[1]);
							table.put("userid", SlahserMetaData.userid);
							// 父id
							table.put("titleid", titleid);
							msg.setValue(table);
							titleid = "";
							MainActivity.this.setTitle(R.string.app_name);
						}
						// 生成的缓存对象删除
						f.delete();
						file2.delete();
						// 通过serve port传递信息
						LoginClientTCP.sendMessage(msg);
					} catch (Exception e) {
						Toast.makeText(MainActivity.this, "Upload failed!",
								Toast.LENGTH_SHORT).show();
					}
				};
			}.start();
		}

	}

	public Vector<ShuoExt> view2 = null;
	public String titleid = "";

	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			fillContent(view2);
		}
	};

	public void fillContent(Vector<ShuoExt> v) {
		// 清屏
		list_linearLayout.removeAllViews();
		// 手动垃圾回收
		System.gc();

		for (final ShuoExt titleInfo : v) {
			// 通过inflater生成说说内容
			LinearLayout line1 = (LinearLayout) LayoutInflater.from(this)
					.inflate(R.layout.item_shuo, null);
			{
				// 页面对象
				LinearLayout info_linearLayout = (LinearLayout) line1
						.findViewById(R.id.info_linearLayout);
				TextView time_textView = (TextView) line1
						.findViewById(R.id.time_textView);
				TextView uname_textView = (TextView) line1
						.findViewById(R.id.uname_textView);

				// 点击用户名触发详细信息
				uname_textView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						MainActivity.this.setTitle("you choose ["
								+ titleInfo.getUname() + "]，can reply");
						titleid = titleInfo.getTitleid();
					}
				});

				uname_textView.setText(titleInfo.getUname());
				// 点击回复则生成一块新的textview
				if (titleInfo.getType().equalsIgnoreCase(Message.SEND_TEXT)) {
					TextView t = new TextView(MainActivity.this);
					t.setTextColor(getResources().getColor(R.color.color2));
					t.setText(titleInfo.getTitletxt());
					info_linearLayout.addView(t);
					// 点击音频
				} else if (titleInfo.getType().equalsIgnoreCase(
						Message.SEND_AMR)) {

					final ButtonExt t = new ButtonExt(MainActivity.this);
					// 为新的lineralayout设置属性
					LinearLayout.LayoutParams lay = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					// 按钮上绘制
					t.setLayoutParams(lay);
					t.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							try {
								// 详情见最下方吧。这玩意
								File f = loadData("amr", t);

								MediaPlayer mediaPlayer = new MediaPlayer();
								if (mediaPlayer.isPlaying()) {
									mediaPlayer.reset();// 重置为初始状态
								}
								mediaPlayer.setDataSource(f.getPath());
								mediaPlayer.prepare();// 缓冲
								mediaPlayer.start();// 开始或恢复播放
							} catch (Exception e) {
								e.printStackTrace();
							}

						}
					});

					t.setText("play");
					t.setFilename(titleInfo.getTitletxt());
					info_linearLayout.addView(t);
				} else if (titleInfo.getType().equalsIgnoreCase(
						Message.SEND_IMAGE)) {
					final ButtonExt t = new ButtonExt(MainActivity.this);
					LinearLayout.LayoutParams lay = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					t.setLayoutParams(lay);
					t.setText("click to view image");
					t.setFilename(titleInfo.getTitletxt());

					t.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							try {
								File f = loadData("image", t);
								// 在新的dialog里面加载图片
								final Dialog d = new Dialog(MainActivity.this);
								ImageView image = new ImageView(
										MainActivity.this);
								image.setOnClickListener(new OnClickListener() {
									// 全凭状态下点击图片则dialog消失
									@Override
									public void onClick(View v) {
										d.hide();
									}
								});
								image.setImageURI(Uri.fromFile(f));
								d.setContentView(image);
								d.show();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});

					info_linearLayout.addView(t);
				}
				time_textView.setText("time:" + titleInfo.getSendcreate());
			}
			// 填充回复从item模板
			for (ReplyExt huifu : titleInfo.getReplys()) {
				LinearLayout line2 = (LinearLayout) LayoutInflater.from(this)
						.inflate(R.layout.item_reply, null);
				line1.addView(line2);

				LinearLayout info_linearLayout = (LinearLayout) line2
						.findViewById(R.id.info_linearLayout);

				TextView time_textView = (TextView) line2
						.findViewById(R.id.time_textView);
				TextView uname_textView = (TextView) line2
						.findViewById(R.id.uname_textView);

				uname_textView.setText(huifu.getUname());

				if (huifu.getType().equalsIgnoreCase(Message.REPLY_TEXT)) {
					TextView t = new TextView(MainActivity.this);
					t.setTextColor(getResources().getColor(R.color.color2));
					t.setText(huifu.getText());
					info_linearLayout.addView(t);
				} else if (huifu.getType().equalsIgnoreCase(Message.REPLY_AMR)) {
					final ButtonExt t = new ButtonExt(MainActivity.this);
					LinearLayout.LayoutParams lay = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					t.setLayoutParams(lay);
					t.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							try {
								File f = loadData("amr", t);
								MediaPlayer mediaPlayer = new MediaPlayer();
								if (mediaPlayer.isPlaying()) {
									// 重置为初始状态
									mediaPlayer.reset();
								}
								mediaPlayer.setDataSource(f.getPath());
								// 缓冲
								mediaPlayer.prepare();
								// 开始或恢复播放
								mediaPlayer.start();
							} catch (Exception e) {
								e.printStackTrace();
							}

						}
					});
					t.setText("play");
					t.setFilename(huifu.getText());
					info_linearLayout.addView(t);
				} else if (huifu.getType().equalsIgnoreCase(Message.REPLY_AMR)) {
					final ButtonExt t = new ButtonExt(MainActivity.this);
					t.setText("click to view image");
					LinearLayout.LayoutParams lay = new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.WRAP_CONTENT,
							LinearLayout.LayoutParams.WRAP_CONTENT);
					t.setLayoutParams(lay);
					t.setFilename(huifu.getText());

					t.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							try {
								File f = loadData("image", t);
								final Dialog d = new Dialog(MainActivity.this);
								ImageView image = new ImageView(
										MainActivity.this);
								image.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										d.hide();
									}
								});
								image.setImageURI(Uri.fromFile(f));
								d.setContentView(image);
								d.show();
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					});
					info_linearLayout.addView(t);
				}
				time_textView.setText("时间:" + huifu.getSendtime());
			}
			list_linearLayout.addView(line1);
		}
	}

	/***
	 * 发送说说监听器
	 * 
	 * @author Slahser
	 * 
	 */
	class sendButtonOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// 如果为空
			if (shuoText.getText().toString().trim().equalsIgnoreCase("")) {
				return;
			}
			// 设置传递信息
			Message msg = new Message();
			if (titleid.trim().equals("")) {
				msg.setType(Message.SEND_TEXT);
				Hashtable<String, Object> table = new Hashtable<String, Object>();
				table.put("txt", shuoText.getText().toString());
				table.put("userid", SlahserMetaData.userid);
				msg.setValue(table);
			} else {
				msg.setType(Message.REPLY_TEXT);
				Hashtable<String, Object> table = new Hashtable<String, Object>();
				table.put("txt", shuoText.getText().toString());
				table.put("titleid", titleid);
				table.put("userid", SlahserMetaData.userid);
				msg.setValue(table);
				titleid = "";
				MainActivity.this.setTitle(R.string.app_name);
			}
			// 发送说说
			LoginClientTCP.sendMessage(msg);
			// 输入框清空
			shuoText.setText("");
		}

	}

	// 双击退出的实现
	int count = 0;

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			this.setTitle(R.string.app_name);
			titleid = "";
			if (count == 1) {
				Toast.makeText(MainActivity.this, "press 2 times to exit",
						Toast.LENGTH_SHORT).show();
				try {
					AcionClientTCP.closeClient();
				} catch (Exception e) {
				}
				try {
					LoginClientTCP.close();
				} catch (Exception e) {
				}
				System.exit(0);
			} else {
				count++;
			}
			return false;
		}
		return super.onKeyUp(keyCode, event);
	}

	private void initView() {
		sendButton = (Button) findViewById(R.id.main_button_send);

		shuoText = (EditText) findViewById(R.id.main_edittext_shuo);

		moreButton = (Button) findViewById(R.id.main_button_more);
		scrollView = (ScrollView) findViewById(R.id.list_scrollView);

		amrButton = (Button) view.findViewById(R.id.more_button_sound);
		imageButton = (Button) view.findViewById(R.id.more_button_image);
		linearLayout = (LinearLayout) findViewById(R.id.menu_linearLayout);
		list_linearLayout = (LinearLayout) findViewById(R.id.list_linearLayout);

	}

	/***
	 * 拍照frame上阵
	 * 
	 * @author Slahser
	 * 
	 */
	public class imageButtonOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			imageFilename = new Date().getTime() + ".jpg";
			File ff = new File(SlahserMetaData.SD_PATH + File.separator,
					imageFilename);
			Uri u = Uri.fromFile(ff);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
			startActivityForResult(intent, 0);
		}
	}

	/***
	 * 录制音频
	 * 
	 * @author Slahser
	 * 
	 */
	class amrButtonOnTouchListener implements OnTouchListener {

		MediaRecorder recorder = null;
		String filename = "";

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == 0) {
				amrButton.setText(">>");
				Toast.makeText(MainActivity.this, "recording!",
						Toast.LENGTH_SHORT).show();
				filename = new Date().getTime() + ".amr";
				recorder = new MediaRecorder();
				recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
				recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
				recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
				recorder.setOutputFile(SlahserMetaData.SD_PATH + File.separator
						+ filename);
				try {
					recorder.prepare();
				} catch (Exception e) {
				}
				recorder.start();
			} else if (event.getAction() == 1) {
				amrButton.setText("record");
				recorder.stop();
				recorder.reset();

				try {
					File f = new File(SlahserMetaData.SD_PATH + File.separator
							+ filename);
					Socket socket = new Socket(SlahserMetaData.IP,
							SlahserMetaData.FILEPORT);
					InputStream in = socket.getInputStream();
					OutputStream out = socket.getOutputStream();
					// 说实话这里不替换成下划线真是闹心。。
					out.write(("upload,amr," + f.length()).getBytes());
					out.flush();
					byte[] b = new byte[1024 * 10];
					in.read(b);

					String serverInfo = new String(b).trim();
					FileInputStream fin = new FileInputStream(f);

					int len = 0;
					while ((len = fin.read(b)) != -1) {
						out.write(b, 0, len);
						out.flush();
					}
					fin.close();
					out.close();
					in.close();
					Message msg = new Message();
					if (titleid.trim().equals("")) {
						msg.setType(Message.SEND_AMR);
						Hashtable<String, Object> table = new Hashtable<String, Object>();
						table.put("text", serverInfo.split(",")[1]);
						table.put("userid", SlahserMetaData.userid);
						msg.setValue(table);
					} else {
						msg.setType(Message.REPLY_AMR);
						Hashtable<String, Object> table = new Hashtable<String, Object>();
						table.put("txt", serverInfo.split(",")[1]);
						table.put("userid", SlahserMetaData.userid);
						table.put("titleid", titleid);
						msg.setValue(table);
						titleid = "";
						MainActivity.this.setTitle(R.string.app_name);
					}
					f.delete();
					LoginClientTCP.sendMessage(msg);
				} catch (Exception e) {
					Toast.makeText(MainActivity.this, "upload failed!",
							Toast.LENGTH_SHORT).show();
				}
			}
			return true;
		}
	}

	// 一段公共代码的提取，真是烦
	public File loadData(String type, ButtonExt t) throws Exception {
		File f = new File(SlahserMetaData.SD_PATH + File.separator,
				t.getFilename());
		if (!f.exists()) {
			Socket socket = new Socket(SlahserMetaData.IP,
					SlahserMetaData.FILEPORT);
			InputStream in = socket.getInputStream();
			OutputStream out = socket.getOutputStream();
			out.write(("download," + type + "," + t.getFilename()).getBytes());
			out.flush();
			byte[] b = new byte[1024];
			in.read(b);
			long size = Long.parseLong(new String(b).trim());

			out.write("OK".getBytes());
			out.flush();

			FileOutputStream outf = new FileOutputStream(f);
			int len = 0;
			long length = 0;
			while ((len = in.read(b)) != -1) {
				length += len;
				outf.write(b, 0, len);
				if (length >= size) {
					break;
				}
			}
			outf.close();
			in.close();
			out.close();
		}
		return f;
	}

}